import axios from 'axios'
import NProgress from 'nprogress'
import Loading from '@/components/Loading/index'

// 封装公共请求方法
class Request {
  constructor(config) {
    // 创建axios实例
    this.instance = axios.create(config)
    // 保存基本信息
    this.interceptors = config.interceptors
    this.showLoading = config.showLoading || true
    this.loading = null
    // 实例请求拦截
    this.instance.interceptors.request.use(this.interceptors.requestInterceptor, this.interceptors.requestInterceptorCatch)
    // 所有请求拦截
    this.instance.interceptors.request.use(
      // 请求成功拦截，所有
      (config) => {
        NProgress.configure({ showSpinner: true })
        NProgress.start()
        if (this.showLoading) this.loading = Loading.start()
        // if (this.showLoading) {
        //   this.loading = Loading.service({
        //     lock: true,
        //     text: '加载中...'
        //   })
        // }
        return config
      },
      // 请求失败拦截，所有
      (err) => {
        return err
      })
    // 所有响应拦截
    this.instance.interceptors.response.use(
      // // 响应成功拦截，所有
      (res) => {
        // if (this.loading) {
        //   this.loading.close()
        // }
        NProgress.done()
        if (this.showLoading) Loading.close()
        return res
      },
      (err) => {
        // 响应失败拦截，所有
        // if (this.loading) {
        //   this.loading.close()
        // }
        NProgress.done()
        if (this.showLoading) Loading.close()
        return err
      }
    )
    //实例响应拦截
    this.instance.interceptors.response.use(this.interceptors.responseInterceptor, this.interceptors.responseInterceptorCatch)
  }
  request(config) {
    return new Promise((resolve, reject) => {
      if (config.loading === false) {
        this.showLoading = config.loading
      }
      this.instance.request(config).then((res) => {
        this.showLoading = true
        resolve(res)
      }).catch((err) => {
        this.showLoading = true
        reject(err)
        return err
      })
    })
  }
  get(config, isShow) {
    if (isShow === false) {
      this.showLoading = isShow
    }
    return this.request({
      url: config,
      method: 'get'
    })
  }
  post(config) {
    return this.request({
      url: config,
      method: 'post'
    })
  }
}

export default Request